// cloudRequest.js

/**
 * 封装微信云托管请求的函数
 * @param {string} url - 请求的路径
 * @param {string} method - 请求的方法，默认为'GET'
 * @param {Object} header - 请求头
 * @param {Object} data - 请求体数据
 * @return {Promise} - 一个Promise对象，包含请求的结果
 */
export function cloudRequest(param) {
	const cloudEnvId = 'prod-5gduafzd5d123d73'; // 微信云托管的环境ID
	const cloudServiceName = 'express-yo52'; // 微信云托管服务名称
	const {
		url,
		method,
		header = {},
		data = {}
	} = param
	return new Promise((resolve, reject) => {
		wx.cloud.callContainer({
			config: {
				env: cloudEnvId,
			},
			path: url,
			method: method,
			header: {
				'X-WX-SERVICE': cloudServiceName,
				'Authorization': 'Bearer ' + uni.getStorageSync('jyu_token') || useUser.token || '',
				...header,
			},
			data: data,
			success: (res) => {
				uni.hideLoading();
				uni.hideToast();
				if (res.statusCode === 200) {
					if (res.data.status !== 200) {
						switch (res.data.status) {
							case 401:
								uni.showModal({
									title: "提示",
									content: "请登录",
									showCancel: false,
									success() {
										setTimeout(() => {
											uni.navigateTo({
												url: "/pages/login/login",
											})
										}, 200);
									},
								});
								break;
							case 404:
								uni.showToast({
									title: '请求地址不存在...',
									duration: 2000,
								})
								break;
							default:
								uni.showToast({
									title: '请重试...',
									duration: 2000,
								})
								break;
						}
					} else {
						resolve(res.data);
					}
				} else {
					reject(new Error(
						`Cloud function call failed with status code: ${res.statusCode}`));
				}
			},
			fail: (error) => {
				uni.hideLoading();
				uni.hideToast();
				reject(error);
			},

		});
	});
}



export default cloudRequest